/*
 * @Author: 周洋 1430536748@qq.com
 * @Date: 2024-07-23 09:51:14
 * @LastEditors: 周洋 1430536748@qq.com
 * @LastEditTime: 2024-08-05 00:04:41
 * @version: 1.2.2
 * @Description: 
 */
import { defineStore } from 'pinia';
import type { IAuthorize } from '@/types/login/index.d';
import { API, ApiLogin, ApiRoutes } from '../api/index';
import { IRoutes, IMeta } from '@/types/login/index.d';
import { IResult } from '../types/index.d';
import RouteView from '@/components/route.vue';
export const authorizeStore = defineStore('authorize', {
    state: () => {
        return {
            accountToken: '',
            userInfo: {},
            whitelistPath: ['/login'],
            routes: [{}]
        } as IAuthorize
    },
    getters: {
        /** 获取令牌 */
        getAccountToken: async (state) => {
            try {
                let result: any = await new API().accountToken();
                return state.accountToken = result.data;
            } catch (error) {
                // 授权失败，跳转到401
                console.log("授权失败异常..." + error);
            }
        },
        /** 获取用户信息 */
        getUserInfo: async (state) => {
            let result: any = await new API().userInfo();
            return state.userInfo = result.data;
        },
        /** 获取路由 */
        getRoutes: async (state) => {
            let user: any = await new API().userInfo();
            Object.assign(state.userInfo, { ...user.data });
            let result: any = await ApiRoutes();
            const accessedRoutes = filterAsyncRoutes(result.data, state.userInfo.roles);
            return Object.assign(state.routes, { ...accessedRoutes });
        }
    },
    actions: {

    },
})




//自动导入views目录下的所有.vue文件
const modules = import.meta.glob('/src/views/**/**.vue');

/**
 * 递归过滤有权限的异步(动态)路由
 * @param routes    接口返回的异步(动态)路由
 * @param roles 用户角色集合
 * @returns 返回用户有权限的异步(动态)路由
 */
function filterAsyncRoutes(routes: Array<IRoutes<IMeta>>, roles: Array<string>) {
    const asyncRoutes: Array<IRoutes<IMeta>> = [];
    routes.forEach((route: IRoutes<IMeta>) => {
        // ES6扩展运算符复制新对象
        const tmpRoute = { ...route };
        // 判断用户(角色)是否有该路由的访问权限
        if (hasPermission(roles, tmpRoute)) {
            if (tmpRoute.component === null || tmpRoute.component === undefined) {
                //解决响应组件警告问题
                tmpRoute.component = markRaw(RouteView);
            } else {
                const layout = modules[`/src/views/${tmpRoute.component}/index.vue`];
                layout ? tmpRoute.component = layout :
                    tmpRoute.component = modules[`/src/views/error/404/index.vue`];
            }
            if (tmpRoute.children) {
                tmpRoute.children = filterAsyncRoutes(tmpRoute.children, roles);
            }
            asyncRoutes.push(tmpRoute);
        }

    });
    return asyncRoutes;
}

/**
 * 使用meta.role确定当前用户是否具有权限
 * @param roles 用户角色集合
 * @param route 路由
 * @returns
 */
const hasPermission = (roles: string[], route: IRoutes<IMeta>) => {
    if (route.meta && route.meta.roles) {
        // 角色【超级管理员】拥有所有权限，忽略校验
        if (roles.includes("root")) {
            return true;
        }
        return roles.some((role) => {
            if (route.meta?.roles) {
                return route.meta.roles.includes(role);
            }
        });
    }
    return false;
};